<template>
  <div class="app">
    <div class="header-box">
      <van-icon name="arrow-left" size="24" @click="goBack" />
      <div class="header-item">
        {{ userInfo.regStatus == 4 ? "资料修改" : "商户入网" }}
      </div>
      <!-- <van-icon name="arrow-left"
                size="24"
      style="visibility: hidden;" />-->
      <span class="header-save" @click="noSave">保存</span>
    </div>
    <Remarks v-if="userInfo.regStatus == 4" :contents="userInfo.remarks" />
    <div class="content-box">
      <!-- 步骤条 -->
      <Steps
        :dataSource="[
          { name: '1基本信息', checked: true },
          { name: '2结算信息', checked: true },
          { name: '3费率信息', checked: true },
          { name: '4附件信息' },
        ]"
      />
      <!-- 主体 -->
      <van-form validate-first input-align="right" ref="form">
        <van-field
          is-link
          readonly
          class="mt-margin"
          v-model="formData.payTypeText"
          label="支付方式"
          placeholder="请选择"
          @click="show1 = true"
        />
        <p
          class="notes"
          v-show="formData.payType == 2 && agentInfo.cardEntryExplain"
        >
          <!-- <p class="notes" v-if="(formData.payType == 2 || formData.payType == 1)  && agentInfo.cardEntryExplain"> -->
          {{ agentInfo.cardEntryExplain }}
        </p>
        <van-field
          v-if="formData.payType == 2"
          v-model="formData.equipmentSN"
          class="mt-margin"
          label="刷卡设备"
          placeholder="请输入刷卡终端SN编号"
          @input="equipmentInput"
          :rules="rules"
          ref="aaabbb"
        >
          <template #button>
            <van-icon name="scan" size="20px" @click="noScan" />
          </template>
        </van-field>
        <van-field
          v-show="
            formData.payType == 2 && !Autonomy && merchant.sk_allowShow == 1
          "
          v-model="formData.rate_sk"
          :disabled="true"
          label="刷卡费率"
          placeholder="请输入刷卡结算费率"
          type="number"
          @input="rateSkInput"
          :rules="[
            {
              validator: valid_sk,
              message: `请输入${Number(merchant.rate_sk_minValue)}-${Number(
                merchant.rate_sk_maxValue
              )}的刷卡费率`,
              trigger: 'onChange',
            },
            {
              pattern: /^(\d+|\d+\.\d{1,2})$/,
              message: '只能输入两位小数哦！',
              trigger: 'onChange',
            },
          ]"
        />
        <van-field
          v-show="
            formData.payType == 2 && !Autonomy && merchant.sk_allowShow == 1
          "
          v-model="formData.rate_fd"
          label="刷卡封顶"
          placeholder="请输入借记卡刷卡封顶值"
          type="number"
          :disabled="true"
          @input="rateFdInput"
        />
        <div class="posLayout">
          <van-field
            class="mt-margin"
            v-model="formData.rate_sm"
            :disabled="true"
            label="扫码费率%"
            placeholder="请输入扫码结算费率"
            type="number"
            @input="rateSmInput"
            :rules="[
              {
                validator: valid_sm,
                message: `请输入${Number(merchant.rate_sm_minValue)}-${Number(
                  merchant.rate_sm_maxValue
                )}的扫码费率`,
                trigger: 'onChange',
              },
              {
                pattern: /^(\d+|\d+\.\d{1,2})$/,
                message: '只能输入两位小数哦！',
                trigger: 'onChange',
              },
            ]"
          />
        </div>

        <van-field
          is-link
          readonly
          class="mt-margin"
          v-model="formData.firstSettleTypeText"
          label="结算周期"
          placeholder="请选择结算周期"
          @click="show2 = true"
        />

        <div class="posLayout" v-if="formData.firstSettleTypeText === 'D0'">
          <van-field
            v-model="formData.rate_d0"
            :disabled="true"
            class="mt-margin"
            label="D0增量费率%"
            placeholder="请输入D0增量费率"
            type="number"
            @input="rateD0Input"
            :rules="[
              {
                validator: valid_d0,
                message: `请输入${Number(merchant.rate_d0_minValue)}-${Number(
                  merchant.rate_d0_maxValue
                )}的D0增量费率`,
                trigger: 'onChange',
              },
              {
                pattern: /^(\d+|\d+\.\d{1,2})$/,
                message: '只能输入两位小数哦！',
                trigger: 'onChange',
              },
            ]"
          />
        </div>
        <p class="notes" v-if="false">
          开启D0交易，则用户自然日交易当日到账，并会对其收 取相应服务费。
        </p>

        <div class="posLayout" v-if="formData.firstSettleTypeText === 'D1'">
          <van-field
            v-model="formData.rate_d1"
            :disabled="true"
            class="mt-margin"
            label="D1增量费率%"
            placeholder="请输入D1增量费率"
            type="number"
            @input="rateD1Input"
            :rules="[
              {
                validator: valid_d1,
                message: `请输入${Number(merchant.rate_d1_minValue)}-${Number(
                  merchant.rate_d1_maxValue
                )}的D1费率`,
                trigger: 'onChange',
              },
              {
                pattern: /^(\d+|\d+\.\d{1,2})$/,
                message: '只能输入两位小数哦！',
                trigger: 'onChange',
              },
            ]"
          />
        </div>
        <!-- 
        <p style="font-size:14px; padding:35px 20px 20px 20px">结算周期增量费率说明：</p>
        <p
          style="font-size:14px; padding:0px 20px 20px 20px; line-height:25px;"
        >结算周期D0，每天的交易额将额外收取D0增量手续费；开启成功后自然日的交易当日到账。</p>
        <p
          style="font-size:14px; padding:0px 20px 20px 20px; line-height:25px;"
        >结算周期D1，周六日的交易金额将额外收取D1增量手续费；开启成功后自然日的交易第二天到账。</p> -->
      </van-form>

      <!-- 以下是弹窗内容 -->
      <van-popup v-model="show1" position="bottom" :style="{ height: '40%' }">
        <van-picker
          title="支付方式"
          show-toolbar
          :columns="payTypesList"
          @confirm="selectPayType"
          @cancel="show1 = false"
        />
      </van-popup>
      <van-popup v-model="show2" position="bottom" :style="{ height: '40%' }">
        <van-picker
          title="结算周期"
          show-toolbar
          :columns="firstSettleTypeListData"
          @confirm="firstSettleTypes"
          @cancel="show2 = false"
        />
      </van-popup>
      <van-button
        block
        type="info"
        color="#FFB72F"
        :disabled="pass"
        @click="nextStep"
        class="next-step-btn"
        >下一步</van-button
      >
    </div>
  </div>
</template>

<script>
import { getSystemRate, getUperAgentRate } from "@/api/rate.js";
import { getAgentSettlementConfigList } from "@/api/merchant";
import { getEquipSn } from "@/api/stores.js";
import { save } from "@/api/stores";
import { getChannelDetail } from "@/api/channel";

export default {
  name: "Step3",
  components: {
    HeaderComp: () => import("@/components/HeaderComps"),
    Remarks: () => import("@/components/Remarks"),
    Steps: () => import("@/components/steps"),
  },
  data() {
    return {
      SNMessage: "设备不存在",

      rate_d0: {
        minValue: 0,
        defaultValue: 0,
        maxValue: 0,
      },
      rate_sk: {
        minValue: 0,
        defaultValue: 0,
        maxValue: 0,
      },
      rate_sm: {
        minValue: 0,
        defaultValue: 0,
        maxValue: 0,
      },
      rate_fd: {
        minValue: 0,
        defaultValue: 0,
        maxValue: 0,
      },
      payTypes: [],
      show1: false,
      show2: false,
      showD0: false,
      showD1: false,
      firstSettleTypeList: [],
      firstSettleTypeListData: [],
      payTypesList: [
        {
          text: "扫码",
          value: 1,
        },
        {
          text: "扫码+刷卡",
          value: 2,
        },
      ],
      formData: {
        payType: "",
        payTypeText: "",
        firstSettleType: "",
        firstSettleTypeText: "",
        rate_d1: "",
        equipmentSN: "",
        rate_sk: "",
        rate_fd: "",
        rate_sm: "",
        rate_d0: "",
      },
      rules: [
        {
          pattern: /^[0-9a-zA-Z]{0,50}$/,
          message: "只支持数字和字母的格式",
          trigger: "onChange",
        },
        {
          validator: this.asyncValidator,
          message: "设备不存在",
          trigger: "onBlur",
        },
      ],
    };
  },
  computed: {
    userInfo() {
      return this.$store.state.user.userInfo;
    },
    agentInfo() {
      return this.$store.state.user.agentInfo;
    },
    Autonomy() {
      return this.$store.state.common.Autonomy;
    },
    merchant() {
      return this.$store.state.merchant;
    },
    pass() {
      return this.$store.getters.valid_step3;
    },
    disSurportCard() {
      let xwStatus = this.$store.state.user.agentInfo.xwStatus;
      return this.formData.merchantType == 3 && xwStatus !== 1;
    },
    firstSettleTypeList() {
      // 当刷卡的时候，过滤D0
      return this.firstSettleTypeListData.map((item) => {
        return {
          ...item,
          disabled: Number(this.formData.payType) === 2 && item.value === 1,
        };
      });
    },
  },
  created() {
    this.payTypes = [
      {
        text: "扫码",
        value: "1",
      },
      {
        text: "扫码+刷卡",
        value: "2",
        disabled: this.disSurportCard,
      },
    ];
    //this.getSystemRates();
    //this.getUperAgentRates();
  },
  mounted() {
    window.AndroidInfo = this.AndroidInfo;
    this.formData = JSON.parse(JSON.stringify(this.$store.state.merchant));
    this.formData.rate_d0 = this.merchant.rate_d0_defaultValue;
    this.formData.rate_d1 = this.merchant.rate_d1_defaultValue;
    this.formData.rate_sk = this.merchant.rate_sk_defaultValue;
    this.formData.rate_fd = this.merchant.rate_fd_defaultValue;
    this.formData.rate_sm = this.merchant.rate_sm_defaultValue;
    console.log(this.formData, this.$store.state.merchant, "this.formData");
    // 获取代理的商户默认费率
    const list = this.agentInfo.agentDefaultMerchantRates;
    if (list.length) {
      const rateSk = list.find((item) => item.rateType === 2) || {
        rateValue: this.merchant.rate_sk_defaultValue,
      };
      const rateSM = list.find((item) => item.rateType === 1) || {
        rateValue: this.merchant.rate_sm_defaultValue,
      };

      this.formData.rate_sk = Number(rateSk.rateValue);
      this.formData.rate_sm = Number(rateSM.rateValue);
    }
    window.scrollTo({
      left: 0,
      top: 0,
      behavior: "smooth",
    });
    this.getAgentSettlementConfigLists();
  },
  watch: {
    "formData.firstSettleType": function (val) {
      if (val == 1) {
        this.payTypesList = [];
        this.payTypes.forEach((item) => {
          if (item.value != "2") {
            this.payTypesList.push(item);
          }
        });
      } else if (val == 2) {
        this.payTypesList = [];
        this.payTypes.forEach((item) => {
          this.payTypesList.push(item);
        });
      }
      if (val) {
        this.agentInfo.agentSettleList.forEach((item) => {
          if (Number(item.settleType) === val) {
            this.$store.commit("setChannelCode", item.channelCode);
          }
        });
      }
    },
    "formData.payType": function (val) {
      console.log(
        this.formData.payType == 2,
        this.Autonomy,
        this.merchant.sk_allowShow == 1
      );
      if (val == 1) {
        this.$store.commit("setRate_fd", this.merchant.rate_fd_defaultValue);
        this.$store.commit("setRate_sk", this.merchant.rate_sk_defaultValue);
      }
      this.getAgentSettlementConfigLists();
      // 当选择了支付方式，且结算周期长度为1时，自动填充
      if (val && this.firstSettleTypeList.length === 1) {
        this.firstSettleType = this.firstSettleTypeList[0].value;
      }
    },
  },
  methods: {
    getAgentSettlementConfigLists() {
      getAgentSettlementConfigList(this.userInfo.agentId).then((res) => {
        if (res.code == 200) {
          this.firstSettleTypeListData = [];
          if (res.data.length > 0) {
            const settleTypeHandler = {
              1: "笔笔到",
              2: "D1",
              3: "T1",
              4: "定时结算",
              6: "定点结算",
            };
            const agentSettleList = this.agentInfo.agentSettleList;
            this.firstSettleTypeListData = res.data
              .map((item) => {
                const channel = agentSettleList.find(
                  (ite) => ite.settleType === item.settleType
                );
                return {
                  ...item,
                  text: settleTypeHandler[item.settleType],
                  value: item.settleType,
                  channelCode:
                    item.channelCode || channel ? channel.channelCode : "",
                };
              })
              // .filter((item) => item.value !== 4);
          }
        }
      });
    },
    AndroidInfo(data) {
      this.formData.equipmentSN = data;
      this.$refs.form.validate();
    },
    noScan() {
      var that = this;
      var u = navigator.userAgent;
      var isAndroid = u.indexOf("Android") > -1 || u.indexOf("Adr") > -1; //android终端
      var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
      if (isAndroid) {
        injectedObject.UseScan();
      }
      if (isiOS) {
        function setupWebViewJavascriptBridge(callback) {
          if (window.WebViewJavascriptBridge) {
            return callback(WebViewJavascriptBridge);
          }
          if (window.WVJBCallbacks) {
            return window.WVJBCallbacks.push(callback);
          }
          window.WVJBCallbacks = [callback]; // 创建一个 WVJBCallbacks 全局属性数组，并将 callback 插入到数组中。
          var WVJBIframe = document.createElement("iframe"); // 创建一个 iframe 元素
          WVJBIframe.style.display = "none"; // 不显示
          WVJBIframe.src = "wvjbscheme://__BRIDGE_LOADED__"; // 设置 iframe 的 src 属性
          document.documentElement.appendChild(WVJBIframe); // 把 iframe 添加到当前文导航上。
          setTimeout(function () {
            document.documentElement.removeChild(WVJBIframe);
          }, 0);
        }
        // 这里主要是注册 OC 将要调用的 JS 方法。
        setupWebViewJavascriptBridge(function (bridge) {
          bridge.callHandler(
            "UseScan",
            { data: "UseScan" },
            function (dataFromOC) {
              console.log(dataFromOC, "dataFromOC--");
              document.getElementById("returnValue").value = dataFromOC;
            }
          );
          bridge.registerHandler(
            "iosSendSNCode",
            function (data, responseCallback) {
              // 回调app
              console.log(data, "message--");
              that.formData.equipmentSN = data;
              that.$refs.form.validate();
              responseCallback(responseData);
            }
          );
        });
      }
    },
    noSave() {
      this.$dialog
        .confirm({
          title: "商户认证",
          message: `<div style="font-size:16px;line-height:12px;">
                <p>确认是否保存资料？</p> </div>`,
          cancelButtonText: "取消",
          // cancelButtonColor: "#FFB72F",
          confirmButtonText: "确认",
          confirmButtonColor: "#FFB72F",
        })
        .then(() => {
          // 保存资料
          this.$store.commit("setComplete", 0);
          this.$toast({
            type: "loading",
            message: "正在提交...",
            forbidClick: true,
            duration: 0,
          });
          save(this.$store.state)
            .then((res) => {
              //   document.title = "提交成功";
              this.$toast.clear();
              if (res.code == 200) {
                this.$toast({
                  type: "success",
                  message: "保存成功",
                  duration: 1500,
                });
                this.$store.dispatch("setSaved", true);
              } else {
                this.$toast({
                  message: res.msg || "操作失败",
                  duration: 2000,
                  forbidClick: true,
                });
              }
            })
            .catch((err) => {
              this.$toast.clear();
              document.title = "返回APP";
            });
          // next();
        })
        .catch(() => {
          // 取消
          // document.title = "返回APP";
          // next();
        });
    },
    asyncValidator(val) {
      // let userInfo = this.$store.state.user.userInfo;
      const agenId = this.userInfo.agentId || this.agentInfo.id;
      console.log(agenId, this.userInfo.agentId, this.agentInfo.id);
      if (/^[0-9a-zA-Z]{0,50}$/.test(val)) {
        return new Promise((resolve, reject) => {
          getEquipSn({ agenId, equipSN: val })
            .then((res) => {
              if (res.code == 200) {
                const { data } = res;
                const { currAgent, payEquip, bind } = data;
                // 判断，任意一个条件不符合就提示错误
                if (!(currAgent && payEquip && bind)) {
                  this.$store.commit("setEquipmentSN", "");
                  const message = {
                    currAgent: "非当前代理设备",
                    payEquip: "请输入未绑定的刷卡终端SN",
                    bind: "该设备已绑定",
                  };
                  // 获取提示文案
                  this.rules[1].message = !currAgent
                    ? message.currAgent
                    : !payEquip
                    ? message.payEquip
                    : !bind
                    ? message.bind
                    : "";
                  resolve(false);
                } else {
                  resolve(true);
                  this.$store.commit("setEquipmentSN", val);
                }
              } else {
                this.rules[1].message = res.msg;
                this.$store.commit("setEquipmentSN", "");
                resolve(false);
              }
            })
            .catch((err) => {
              console.log(err, "err");
              this.rules[1].message = "校验失败";
              this.$store.commit("setEquipmentSN", "");
              resolve(false);
            });
        });
      }
    },
    equipmentInput(val) {},
    rateSkInput(val) {
      this.$store.commit("setRate_sk", val);
    },
    rateFdInput(val) {
      this.$store.commit("setRate_fd", val);
    },
    rateSmInput(val) {
      this.$store.commit("setRate_sm", val);
    },
    rateD0Input(val) {
      this.$store.commit("setRate_d0", {
        minValue: this.rate_d0.minValue,
        maxValue: this.rate_d0.maxValue,
        value: val,
      });
    },
    rateD1Input(val) {
      this.$store.commit("setRate_d1", {
        //minValue: this.rate_d1.minValue,
        //maxValue: this.rate_d1.maxValue,
        value: val,
      });
    },
    valid_sk(val) {
      let flag = false;
      if (
        val >= this.merchant.rate_sk_minValue &&
        val <= this.merchant.rate_sk_maxValue
      ) {
        flag = true;
      }
      return flag;
    },
    valid_fd(val) {
      let flag = false;
      if (
        val >= Number(this.merchant.rate_fd_minValue) &&
        val <= Number(this.merchant.rate_fd_maxValue)
      ) {
        flag = true;
      }
      return flag;
    },
    valid_sm(val) {
      let flag = false;
      if (
        val >= this.merchant.rate_sm_minValue &&
        val <= this.merchant.rate_sm_maxValue
      ) {
        flag = true;
      }
      return flag;
    },
    valid_d0(val) {
      let flag = false;
      if (
        val >= this.merchant.rate_d0_minValue &&
        val <= this.merchant.rate_d0_maxValue
      ) {
        flag = true;
      }
      return flag;
    },
    valid_d1(val) {
      let flag = false;
      if (
        val >= Number(this.merchant.rate_d1_minValue) &&
        val <= Number(this.merchant.rate_d1_maxValue)
      ) {
        flag = true;
      }
      return flag;
    },
    goBack() {
      this.$router.push({
        path: "/step2",
      });
    },
    selectPayType(data, index) {
      this.formData.payTypeText = data.text;
      this.formData.payType = data.value;
      this.$store.commit("setPayType", data);
      if (data.value == 1) {
        this.$store.commit("setEquipmentSN", "");
      }
      this.show1 = false;
    },
    firstSettleTypes(data, index) {
      this.formData.firstSettleTypeText = data.text;
      this.formData.firstSettleType = data.value;
      this.$store.commit("firstSettleType", data);
      this.$store.commit("setChannelCode", data.channelCode);
      this.show2 = false;
    },
    nextStep() {
      this.$toast.loading("加载中，请稍等");
      const settle = this.firstSettleTypeListData.find(
        (item) => item.value === this.formData.firstSettleType
      );
      console.log(settle, "settle");
      if (settle && settle.channelId) {
        getChannelDetail(settle.channelId).then((res) => {
          const { data, code } = res;
          if (code === 200) {
            const { supportTradeType } = data;
            if (
              ![2, 3].includes(supportTradeType) &&
              this.formData.payType == 2
            ) {
              this.$toast.fail("该结算周期暂不支持刷卡");
              this.formData.firstSettleType = "";
              this.formData.firstSettleTypeText = "";
              this.$store.commit("firstSettleType", {});
            } else {
              this.$toast.clear();
              this.$router.push({
                path: "/step4",
              });
            }
          }
        });
      } else {
        this.$toast.clear();
        // 无法获取当前结算周期的支付渠道时
        this.$router.push({
          path: "/step4",
        });
      }
    },
    getSystemRates() {
      getSystemRate().then((res) => {
        if (res.code == 200) {
          const { data } = res;
          data.forEach((i) => {
            switch (i.rateType) {
              case 1:
                this.rate_sk.maxValue = i.maxValue;
                this.rate_sk.defaultValue = i.defaultValue;
                break;
              case 2:
                this.rate_d0.maxValue = i.maxValue;
                this.rate_d0.minValue = i.minValue;
                this.rate_d0.defaultValue = i.defaultValue;

                this.rate_d1.maxValue = i.maxValue;
                this.rate_d1.minValue = i.minValue;
                this.rate_d1.defaultValue = i.defaultValue;
                break;
              case 3:
                this.rate_sm.maxValue = i.maxValue;
                this.rate_sm.defaultValue = i.defaultValue;
                break;
              case 4:
                this.rate_fd.maxValue = i.maxValue;
                this.rate_fd.defaultValue = i.defaultValue;
                break;
            }
          });
        }
      });
    },
    getUperAgentRates() {
      getUperAgentRate(1).then((res) => {
        if (res.code == 200) {
          const { data } = res;
          data.forEach((i) => {
            switch (i.rateType) {
              case 2:
                this.rate_sk.minValue = i.rateValue;
                break;
              case 4:
                // this.rate_d0.minValue = i.rateValue;
                break;
              case 1:
                this.rate_sm.minValue = i.rateValue;
                break;
              case 3:
                this.rate_fd.minValue = i.rateValue;
            }
          });
        }
      });
    },
  },
};
</script>
<style scoped lang="less">
/deep/.van-picker-column__item--selected {
  color: #ff9600 !important;
}
/deep/.van-picker__confirm {
  color: #ff9600 !important;
}
/deep/.van-field__label {
  color: #323233;
}
/deep/.van-dialog__content {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 57px 0;
}
.next-step-btn {
  width: 80%;
  margin: 100px auto;
}
.app {
  background: #f9f9f9;
  height: 100vh;
}
.content-box {
  background: #f9f9f9;
  padding-bottom: 1px;
  box-sizing: border-box;
}

.mt-margin {
  margin-top: 24px;
}
.example-img {
  width: 420px;
  height: 270px;
}

.header-box {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32px;
  border-bottom: 1px solid #d7d7d7;
  font-size: 36px;
  background: #fff;
  .header-item {
    font-weight: 500;
    color: #131313;
  }
  .header-save {
    color: #ffb72f;
    font-size: 28px;
  }
}
.app {
  background: #f9f9f9;
}
.notes {
  font-size: 28px;
  font-weight: 400;
  color: #131313;
  opacity: 0.8;
  padding: 24px 31px 0;
  line-height: 50px;
}
.posLayout {
  position: relative;
}
.posRight {
  position: absolute;
  right: 20px;
  top: 7px;
  color: #323233;
  font-size: 14px;
}
.black {
  color: #323233;
}
.gray {
  color: #c8c9cc;
}
</style>
